const fs = require('fs');
const join = require('path').join;
const mongoose = require('mongoose');
const ServerConfig = require('../config/serverConfig');
let dbReconnectSize = 0;
let isNotReconnectIng = true;
let DatabaseManager = {
    init: function(){
        let self = this;
        self.setupSchema();
        return self.connect();
    },
    connect:function(){
        let db = null;
        try{
            let self = this;
            mongoose.connect(ServerConfig.chatMongdbUrl,
                ServerConfig.mongodbOptions
            );
            db = mongoose.connection;
            db.on('error', (error) => {
                logError.error('database connect error', error);
            }).on('disconnected', (error) => {
                if(isNotReconnectIng){
                    if(dbReconnectSize<=ServerConfig.maxMongodbReconnnect){
                        dbReconnectSize++;
                        isNotReconnectIng = false;
                        setTimeout(() => {
                            isNotReconnectIng = true;
                            self.connect();
                        }, ServerConfig.maxMongodbReconnnectInterval);
                        logError.error('database disconnected error', '断网重连第'+dbReconnectSize+'次');
                    }else{
                        logError.error('database disconnected error', '断网重连超过'+ServerConfig.maxMongodbReconnnect+'次，放弃重连');
                    }
                }
            });
        }catch (e){
            logError.error('database reconnection error', e );
        }
        return db;
    },
    setupSchema:function(){
        let models = join(__dirname,'..','model');
        fs.readdirSync(models)
            .filter(file => ~file.search(/^[^\.].*\.js$/))
            .forEach(file => require(join(models, file)));
        commonUtil.consoleSysInfo("Schema初始化完成");
    }
};
module["exports"] = DatabaseManager;